/**
 * 读者写者问题
 * 读者优先
 * 青儿哥哥
 * 博客园
 * 2017-09-27
 * */

#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
#include<unistd.h>

#define R_NUM 10 //读者个数
#define W_NUM 3 //写者个数

pthread_t rpt[R_NUM];//读者线程的id
pthread_t wpt[W_NUM];//写者线程的id

int readercnt = 0;


int buffer = 100;

pthread_mutex_t buffer_mutex;//缓冲区的临界区

pthread_mutex_t readercnt_mutex;//读者数量的临界区




void write()
{
    int rd = rand()%100;
    buffer = rd;
    printf("写者写：%d\n",buffer);
}
void read()
{
    printf("读者读：%d\n",buffer);
}

void *reader(void *arg)
{
    (void)arg;
    while(1)
    {
        pthread_mutex_lock(&readercnt_mutex);
        readercnt++;
        if(readercnt == 1)
        {
            pthread_mutex_lock(&buffer_mutex);
        }
        pthread_mutex_unlock(&readercnt_mutex);

        read();

        pthread_mutex_lock(&readercnt_mutex);
        readercnt--;
        if(readercnt == 0)
        {
            pthread_mutex_unlock(&buffer_mutex);
        }
        pthread_mutex_unlock(&readercnt_mutex);
        sleep(1);

    }
    return NULL;

}
void *writer(void *arg)
{
    (void)arg;
    while(1)
    {
        pthread_mutex_lock(&buffer_mutex);
        write();
        pthread_mutex_unlock(&buffer_mutex);
        sleep(1);
    }
    return NULL;
}

int main()
{
    //初始化互斥体
    pthread_mutex_init(&buffer_mutex,NULL);
    pthread_mutex_init(&readercnt_mutex,NULL);

    int i = 0;
    for(i = 0;i < R_NUM;i++)
    {
        pthread_create(&rpt[i],NULL,reader,NULL);
    }
    for(i = 0;i < W_NUM;i++)
    {
        pthread_create(&wpt[i],NULL,writer,NULL);
    }

    for(i = 0;i < R_NUM;i++)
    {
        pthread_join(rpt[i],NULL);
    }
    for(i = 0;i < W_NUM;i++)
    {
        pthread_join(wpt[i],NULL);
    }

    pthread_mutex_destroy(&buffer_mutex);
    pthread_mutex_destroy(&readercnt_mutex);


    return 0;
}
